package com.bupt.ilink.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bupt.ilink.entity.Studyspace.tree.StudyTreeFavorite;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.service.StudyTreeFavoriteService;
import com.bupt.ilink.mapper.StudyTreeFavoriteMapper;
import com.bupt.ilink.utils.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author LENOVO
* @description 针对表【study_tree_favorite】的数据库操作Service实现
* @createDate 2024-09-10 20:45:00
*/
@Service
@Slf4j
public class StudyTreeFavoriteServiceImpl extends ServiceImpl<StudyTreeFavoriteMapper, StudyTreeFavorite>
    implements StudyTreeFavoriteService{
    @Autowired
    private StudyTreeFavoriteMapper studyTreeFavoriteMapper;

    @Override
    public boolean insertFavoriteTree(String userId, Long treeId){
        try{
            // 检查是否已经存在相同的 userId 和 treeId
            Long count = studyTreeFavoriteMapper.selectCount(
                    new LambdaQueryWrapper<StudyTreeFavorite>()
                            .eq(StudyTreeFavorite::getUserId, userId)
                            .eq(StudyTreeFavorite::getId, treeId)
            );

            // 如果已存在则不插入，直接返回 false 表示未插入
            if (count > 0) {
                log.warn("User '{}' 已收藏 treeId '{}'，跳过插入", userId, treeId);
                return false;
            }

            StudyTreeFavorite studyTreeFavorite = new StudyTreeFavorite();
            // 雪花算法生成的ID
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
            Long favoriteId = idGenerator.nextId();

            studyTreeFavorite.setFavoriteId(favoriteId);
            studyTreeFavorite.setUserId(userId);
            studyTreeFavorite.setId(Long.valueOf(treeId));

            studyTreeFavoriteMapper.insert(studyTreeFavorite);
            return true;
        }catch (Exception e){
            log.error("insertFavoriteTree函数"+e.getMessage());
            return false;
        }
    }

    @Override
    public List<StudyTreeFavorite> getFavoriteListByUserId(String userId) {
        return studyTreeFavoriteMapper.selectList(
                new LambdaQueryWrapper<StudyTreeFavorite>()
                        .eq(StudyTreeFavorite::getUserId, userId)
        );
    }

}




